/*
 * @LastEditTime: 2023-02-28 11:30:54
 */
import Axios from "axios";
import { NewMusic } from "../Models/NewMusic.schema";
import { createNewMusicDataDTO } from "../DTO/NewMusic.dto";
import { createMusicDTO } from "../DTO/Music.dto";
import { isExistsforTitle } from "../hook"

export class NewMusicController {
  constructor(private readonly newMusicModel: typeof NewMusic) { }

  /**
 * 创建专辑
 * @param dto 数据传输对象
 * @returns 返回创建对象
 */

  async createNewMusicItem(dto: createNewMusicDataDTO) {
    try {
      return {
        code: 200,
        message: "创建成功",
        data: await NewMusic.create(dto),
      };
    } catch (error) {
      return await error;
    }
  }



  //查询全部数据
  async findAll() {
    try {
      if (await this.newMusicModel.find().count() != 0)
        return {
          code: 200,
          message: "查询成功",
          data: await this.newMusicModel.find(),

        };
      else
        return {
          code: 400,
          message: "该数据集不存在数据"
        }
    }
    catch (error) {
      return await error;
    }
  }

  // 获取新碟信息
  async getNew(type: any) {
    console.log(type)
    if (await this.newMusicModel.find({ name: type }).count() == 0) {
      try {
        const data = await Axios.get(`http://162.14.104.16:3005/top/song?type=0`)
        const res = data.data as {
          code: number,
          data: {
            id: string,
            name: string,
            picUrl: string,
            mp3Url: string,
            lMusic: {
              playTime: string;
            },
            album: {
              id: string
              name: string,
            },
            artists: {
              id: string,
              name: string,
            }
          }[]
        }
        let arr: createMusicDTO[] = [];
        for (let i = 0; i < res.data.length; i++) {
          let tempData = {
            _id: res.data[i].id,
            name: res.data[i].name,
            lyricsId: res.data[i].id,
            cover: res.data[i].picUrl,
            singer: res.data[i].artists,
            album: res.data[i].album,
            time: res.data[i].lMusic.playTime,
            link: res.data[i].mp3Url,
          } as createMusicDTO
          arr.push(tempData)
        }
        console.log(arr)
        await this.createNewMusicItem({
          name: type,
          data: arr,
        });
        return {
          code: 200,
          message: '查询成功2',
          data: await this.newMusicModel.find({ name: type }),
        }
      } catch (error) {
        return error;
      }
    }
    else
      return {
        code: 200,
        message: '查询成功1',
        data: await this.newMusicModel.find({ name: type }),
      }
  }
}